package com.gin.kotlin.no_gay_alliance.fragment.post

import android.os.Bundle
import android.view.View
import com.gin.kotlin.no_gay_alliance.adapter.post.TopicKeyAdapter
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingFragment
import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.kotlin.no_gay_alliance.databinding.FragmentPostTopicKeyBinding
import com.gin.kotlin.no_gay_alliance.provider.ngaphp.TopicKeyProvider
import com.gin.nga.response.topic.TopicKey

class PostTopicKeyFragment : AbstractBindingFragment<FragmentPostTopicKeyBinding>(), RCallback<List<TopicKey>, Long> {
    private lateinit var adapter: TopicKeyAdapter
    private var forumId: Long = 0

    override fun onCreateView() {
        val b = this.b ?: return

        b.swipeRefreshLayout.setOnRefreshListener { request(true) }
        this.adapter = TopicKeyAdapter(requireContext(), handler!!)

        b.recyclerView.adapter = this.adapter
        request()
    }

    private fun request(ignoreCache: Boolean = false) {
        val b = this.b ?: return
        b.tvWarning.visibility = View.GONE
        b.recyclerView.visibility = View.VISIBLE
        b.swipeRefreshLayout.isRefreshing = true
        TopicKeyProvider.getInstance().enqueue(params = forumId, ignoreCache = ignoreCache, callback = this)
    }

    override fun handleArguments(bundle: Bundle) {
        super.handleArguments(bundle)
        this.forumId = bundle.getLong(KEY_ARGUMENT)
    }

    override fun onSuccess(data: List<TopicKey>, ignoreCache: Boolean) {
        val b = this.b ?: return
        b.swipeRefreshLayout.isRefreshing = false
        adapter.replaceData(data)
    }

    override fun onError(errorMessage: String) {
        val b = this.b ?: return
        ui {
            b.tvWarning.visibility = View.VISIBLE
            b.recyclerView.visibility = View.GONE
            b.tvWarning.text = errorMessage
            b.swipeRefreshLayout.isRefreshing = false
        }
    }

    companion object {
        private const val KEY_ARGUMENT = "forumId"
        fun newInstance(forumId: Long): PostTopicKeyFragment {
            val args = Bundle()
            args.putLong(KEY_ARGUMENT, forumId)
            val fragment = PostTopicKeyFragment()
            fragment.arguments = args
            return fragment
        }
    }
}